import type { Layer } from '@shared/schema'
import { Eye, EyeOff, GripVertical, Image as ImageIcon, Lock, Square, Trash2, Type, Unlock } from 'lucide-react'
import { useState } from 'react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { ScrollArea } from '@/components/ui/scroll-area'

interface LayersPanelProps {
  layers: Layer[]
  selectedLayerId: string | null
  onLayerSelect: (layerId: string) => void
  onLayerUpdate: (layerId: string, updates: Partial<Layer>) => void
  onLayerDelete: (layerId: string) => void
  onLayerReorder: (fromIndex: number, toIndex: number) => void
}

export function LayersPanel({
  layers,
  selectedLayerId,
  onLayerSelect,
  onLayerUpdate,
  onLayerDelete,
  onLayerReorder,
}: LayersPanelProps) {
  const [draggedIndex, setDraggedIndex] = useState<number | null>(null)

  const getLayerIcon = (type: Layer['type']) => {
    switch (type) {
      case 'text':
        return <Type className="w-4 h-4" />
      case 'shape':
        return <Square className="w-4 h-4" />
      case 'image':
        return <ImageIcon className="w-4 h-4" />
      default:
        return null
    }
  }

  const getLayerTypeName = (type: Layer['type']) => {
    switch (type) {
      case 'text':
        return '文字'
      case 'shape':
        return '形状'
      case 'image':
        return '图像'
      default:
        return '图层'
    }
  }

  // Render layer item
  const renderLayerItem = (layer: Layer, index: number) => {
    const isSelected = layer.id === selectedLayerId
    const isDragging = draggedIndex === index

    return (
      <div
        key={layer.id}
        draggable
        onDragStart={(e) => {
          setDraggedIndex(index)
          e.dataTransfer.effectAllowed = 'move'
          e.dataTransfer.setData('layerId', layer.id)
        }}
        onDragEnd={() => {
          setDraggedIndex(null)
        }}
        onDragOver={(e) => {
          e.preventDefault()
          e.dataTransfer.dropEffect = 'move'
        }}
        onDrop={(e) => {
          e.preventDefault()
          e.stopPropagation()

          if (draggedIndex !== null && index !== draggedIndex) {
            onLayerReorder(draggedIndex, index)
          }

          setDraggedIndex(null)
        }}
        className={`group rounded-md p-2 cursor-pointer transition-all hover-elevate ${
          isSelected ? 'bg-accent' : ''
        } ${isDragging ? 'opacity-50' : ''}`}
        onClick={() => onLayerSelect(layer.id)}
        data-testid={`layer-item-${layer.id}`}
      >
        <div className="flex items-center gap-2">
          {/* Drag Handle */}
          <div className="shrink-0 cursor-grab active:cursor-grabbing opacity-0 group-hover:opacity-100 transition-opacity">
            <GripVertical className="w-4 h-4 text-muted-foreground" />
          </div>

          {/* Layer Icon */}
          <div className="shrink-0 w-8 h-8 rounded bg-muted flex items-center justify-center text-muted-foreground">
            {getLayerIcon(layer.type)}
          </div>

          {/* Layer Info */}
          <div className="flex-1 min-w-0 overflow-hidden">
            <div className="text-sm font-medium truncate">
              {layer.name || layer.content || `${getLayerTypeName(layer.type)} ${layer.id}`}
            </div>
            <div className="text-xs text-muted-foreground truncate">
              {getLayerTypeName(layer.type)}
              {' · '}
              {Math.round(layer.width)}
              {' × '}
              {Math.round(layer.height)}
            </div>
          </div>

          {/* Actions */}
          <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
            <Button
              size="icon"
              variant="ghost"
              className="h-7 w-7"
              onClick={(e) => {
                e.stopPropagation()
                onLayerUpdate(layer.id, { visible: !layer.visible })
              }}
              data-testid={`button-toggle-visibility-${layer.id}`}
            >
              {layer.visible ? <Eye className="w-3.5 h-3.5" /> : <EyeOff className="w-3.5 h-3.5" />}
            </Button>
            <Button
              size="icon"
              variant="ghost"
              className="h-7 w-7"
              onClick={(e) => {
                e.stopPropagation()
                onLayerUpdate(layer.id, { locked: !layer.locked })
              }}
              data-testid={`button-toggle-lock-${layer.id}`}
            >
              {layer.locked ? <Lock className="w-3.5 h-3.5" /> : <Unlock className="w-3.5 h-3.5" />}
            </Button>
            <Button
              size="icon"
              variant="ghost"
              className="h-7 w-7 text-destructive hover:text-destructive"
              onClick={(e) => {
                e.stopPropagation()
                onLayerDelete(layer.id)
              }}
              data-testid={`button-delete-${layer.id}`}
            >
              <Trash2 className="w-3.5 h-3.5" />
            </Button>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="flex flex-col h-full w-full">
      {/* Header */}
      <div className="p-4 border-b shrink-0">
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-sm font-semibold">图层</h2>
          <Badge variant="secondary" className="text-xs" data-testid="layer-count">
            {layers.length}
          </Badge>
        </div>
        <Input
          placeholder="搜索图层..."
          className="h-8 text-sm w-full"
          data-testid="input-search-layers"
        />
      </div>

      {/* Layers List */}
      <ScrollArea className="flex-1 h-0">
        {layers.length === 0
          ? (
              <div className="flex flex-col items-center justify-center h-full p-6 text-center">
                <Square className="w-12 h-12 text-muted-foreground/50 mb-3" />
                <p className="text-sm text-muted-foreground">暂无检测到的图层</p>
                <p className="text-xs text-muted-foreground mt-1">
                  上传图片开始分析
                </p>
              </div>
            )
          : (
              <div className="p-2 space-y-1 w-full">
                {layers.map((layer, index) => renderLayerItem(layer, index))}
              </div>
            )}
      </ScrollArea>
    </div>
  )
}
